package servlet;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
//将项目中的web.xml文件解析，返回Servlet名称和访问url的偶对
public class Parser {
	List<Pair> list;

	public Parser() {
		list = new ArrayList<Pair>();
	}

	public List<Pair> xmlParser(String projectPath) {
		try {

			
			SAXReader saxReader = new SAXReader();
			
			File file = new File(projectPath + "\\WEB-INF\\web.xml");
			if(file.exists()){
				Document doc = saxReader.read(file);
				Element root = doc.getRootElement();
				List<Element> sList = (List<Element>) root.elements("servlet");
				List<Element> smList = (List<Element>) root
						.elements("servlet-mapping");

				for (Element se : sList) {
					String sName = se.element("servlet-name").getTextTrim();
					String servletClass = se.element("servlet-class").getTextTrim();

					for (Element sme : smList) {
						String smName = sme.element("servlet-name").getTextTrim();
						if (sName.equals(smName)) {
							String urlPattern = sme.element("url-pattern").getTextTrim();
							
//							System.out.println(urlPattern);
//							System.out.println(servletClass);
//							System.out.println();
							
							Pair pair = new Pair();
							pair.setUrlPattern(urlPattern);
							pair.setServletClass(servletClass);
							list.add(pair);
						}
					}
				}
			}
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return list;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String projectPath = "C:\\apache-tomcat-5.5.28\\webapps\\BookStore";
		new Parser().xmlParser(projectPath);
	}

}
